package com.zpark.service.impl;

import com.zpark.dao.IAccountDao;
import com.zpark.pojo.Account;
import com.zpark.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * 账户业务层接口实现类
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao accountDao;

    /**
     * 在方法上使用 @Transactional 注解
     *
     * 转账业务
     * @param id1 转出账户id
     * @param id2 转入账户id
     * @param money 转账金额
     */
    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, timeout = 10, readOnly = false)
    public void transfer(Integer id1, Integer id2, Double money) {

        // 查询转出id账户数据
        Account acc1 = accountDao.selectById(id1);
        // 判断金额是否充足
        if (acc1.getMoney() < money) {
            // 转账错误，余额不足
            throw new RuntimeException("余额不足");
        }
        // 查询转入id账户数据
        Account acc2 = accountDao.selectById(id2);
        // 执行转账业务
        // 将id1账户的money转出
        accountDao.updateById(id1, acc1.getMoney() - money);
        // 人为制作错误
        int num = 2/0;
        // 修改id2的money
        accountDao.updateById(id2, acc2.getMoney() + money);

    }
}
